defmodule GiomWeb.IstController do
  use GiomWeb, :controller

  alias Giom.Accounting
  alias Giom.Accounting.Ist
 

  def index(conn, _params) do
    ists = Accounting.list_ists()
    render(conn, "index.html", ists: ists)
  end

  def new(conn, _params) do
    changeset = Accounting.change_ist(%Ist{})
    render(conn, "new.html", changeset: changeset)
  end
  
  def get_stockname(conn, %{"code" => stock_code}) do
    json(conn, Accounting.get_stock!(stock_code).name)
  end
  
  def create(conn, %{"ist" => ist_params}) do
    case Accounting.create_ist(ist_params) do
      {:ok, ist} ->
        conn
        |> put_flash(:info, "Ist created successfully.")
        |> redirect(to: ist_path(conn, :show, ist))
      {:error, %Ecto.Changeset{} = changeset} ->
        render(conn, "new.html", changeset: changeset)
    end
  end

  def show(conn, %{"id" => id}) do
    ist = Accounting.get_ist!(id)
    render(conn, "show.html", ist: ist)
  end

  def edit(conn, %{"id" => id}) do
    ist = Accounting.get_ist!(id)
    changeset = Accounting.change_ist(ist)
    render(conn, "edit.html", ist: ist, changeset: changeset)
  end

  def update(conn, %{"id" => id, "ist" => ist_params}) do
    ist = Accounting.get_ist!(id)

    case Accounting.update_ist(ist, ist_params) do
      {:ok, ist} ->
        conn
        |> put_flash(:info, "Ist updated successfully.")
        |> redirect(to: ist_path(conn, :show, ist))
      {:error, %Ecto.Changeset{} = changeset} ->
        render(conn, "edit.html", ist: ist, changeset: changeset)
    end
  end

  def delete(conn, %{"id" => id}) do
    ist = Accounting.get_ist!(id)
    {:ok, _ist} = Accounting.delete_ist(ist)

    conn
    |> put_flash(:info, "Ist deleted successfully.")
    |> redirect(to: ist_path(conn, :index))
  end
end
